using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VActSkillEffect : MonoBehaviour
{
    public VActProcessor mainProcessor;
    public VActProcessor collisionProcessor;
    public VActor curActor;

    public void LoadEffect(VActProcessor processor)
    {
        mainProcessor = processor;
        OnTEnterAction += Slash;
    }

    public void LoadEffect(VActProcessor processor, string skillEffectCode)
    {
        mainProcessor = processor;
        if (skillEffectCode == "DarkBullet")
        {
            //先朝向目标
            var param = processor.data.cache["DarkBullet"] as VActSkillParam_Target;


            var rigi = gameObject.AddComponent<Rigidbody>();
            rigi.useGravity = false;
            rigi.AddForce(CalculateForce(param.targetTransform, 10), ForceMode.Impulse);
            //添加碰撞回调 可以使用Func函数逼近
            FuncObserver disFunc = new FuncObserver()
            {
                complete = () => CalculateDistance(param.targetTransform) <= 0.1f,
                end = ()=>{
                    var hit = Instantiate("DarkBulletHit".ToPrefab());
                    VAudio.PlayAudio("DarkBulletHit_wav".ToAudioClip());
                    hit.transform.position = transform.position;
                    // param.targetProcessor.behaviour.Hit();
                    //增加打击特效
                    Destroy(gameObject);
                    Destroy(hit, 2f);
                }
            }.Subscribe();

            Destroy(gameObject, 5f);
        }
    }

    public void Slash(VActor actor)
    {
        actor.input.ForceDoAct("hit");
        mainProcessor.WriteSkillParam("Slash", actor.gameObject.name);
    }
    public Vector3 CalculateForce(Transform targetTransform, float mag)
    {
        Vector3 direction = (targetTransform.position - transform.position).normalized;
        return direction * mag;
    }
    public float CalculateDistance(Transform targetTransform)
    {
        return (targetTransform.position - transform.position).magnitude;
    }

    #region  Collision
    public Action<VActor> OnTEnterAction;
    public Action<VActor> OnTExitAction;
    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent<VActor>(out var actor))
        {
            curActor = actor;
            collisionProcessor = other.GetComponent<VActProcessor>();
            OnTEnterAction?.Invoke(curActor);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        OnTExitAction?.Invoke(curActor);
        curActor = null;
        collisionProcessor = null;
    }
    #endregion
}
public class VActSkillParam_Target
{
    public VActor actor;
    public VActProcessor targetProcessor;
    public Transform targetTransform;
}

